package org.fangzz.cameramgr.cameramonitor.utils;

import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.WinNT;

import java.io.IOException;
import java.lang.reflect.Field;

public class KillProcessUtil {

    public static void killProcessTree(Process process) {
        Field field = null;
        try {
            field = process.getClass().getDeclaredField("handle");
            field.setAccessible(true);
            long hand = field.getLong(process);
            Kernel32 kernel32 = Kernel32.INSTANCE;
            WinNT.HANDLE handle = new WinNT.HANDLE();
            handle.setPointer(Pointer.createConstant(hand));
            int ret = kernel32.GetProcessId(handle);
            Long PID =Long.valueOf(ret);
            String cmd = "";
            if (PID !=null){
                cmd = "cmd.exe /c taskkill /PID" + PID + " /F /T";
            }
            Runtime runtime = Runtime.getRuntime();
            Process killProcess = runtime.exec(cmd);
            killProcess.waitFor();
            killProcess.destroy();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
